package com.zhang.sort;

import java.util.Arrays;

/**
 * @author zhang
 * @time 2022/01/10 22:35:00
 */
public class MergeSort {
    public static void sort(int[] array) {
        if (array.length < 2) {
            return;
        }
        //Divide this array into half
        int middle = array.length / 2;
        int[] left = new int[middle];
        for (int i = 0; i < left.length; i++) {
            left[i] = array[i];
        }
        int[] right = new int[array.length - middle];
        for (int i = middle; i < array.length; i++) {
            right[i - middle] = array[i];
        }
        //Sort each half
        sort(left);
         sort(right);
        //Merge the result
        merge(left,right,array);
    }

    private static void  merge(int[] left, int[] right, int[] result) {

        int i = 0, j = 0, k = 0;

        while (i < left.length && j < right.length) {
            if (left[i] <= right[j]) {
                result[k++] = left[i++];
            } else {
                result[k++] = right[j++];
            }
        }
        while (i < left.length) {
            result[k++] = left[i++];
        }
        while (j < right.length) {
            result[k++] = right[j++];
        }
        System.out.println(Arrays.toString(result));

    }

}
